<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="属性名称" prop="ruleName">
        <el-input
          v-model="queryParams.ruleName"
          placeholder="请输入属性名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态位" prop="ruleStatus">
        <el-select v-model="queryParams.ruleStatus" placeholder="请选择状态位" clearable>
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建人" prop="createdBy">
        <el-input
          v-model="queryParams.createdBy"
          placeholder="请输入创建人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['rule:ruleinfo:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['rule:ruleinfo:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['rule:ruleinfo:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['rule:ruleinfo:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ruleinfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" />
      <el-table-column label="属性名称" align="center" prop="ruleName" />
      <el-table-column label="属性模板" align="center" prop="ruleAttrTemplate" >
        <template slot-scope="scope">
          <p v-html="scope.row.ruleAttrTemplate"></p>
        </template>
      </el-table-column>
      <el-table-column label="状态位" align="center" prop="ruleStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.ruleStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createdBy" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['rule:ruleinfo:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['rule:ruleinfo:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改规格属性对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="属性名称" prop="ruleName">
          <el-input v-model="form.ruleName" placeholder="请输入属性名称" />
        </el-form-item>
        <el-form-item label="属性模板" prop="ruleAttrTemplate">
<!--          <el-input v-model="form.ruleAttrTemplate" type="textarea" placeholder="请输入内容" />-->

          <div :key="tag"
               v-for="(tag,index) in ruleAttrList">
            <el-tag
              closable
              type="danger"
              :disable-transitions="false"
              @close="handleRuleClose(index)">
              {{tag.attrName}}
            </el-tag>
            <br/>
            <el-tag
              :key="attr"
              v-for="(attr,ruleIndex) in tag.attrList"
              closable
              type="success"
              :disable-transitions="false"
              @close="handleAttrClose(index,ruleIndex)">
              {{attr}}

            </el-tag>
            <el-button  class="button-new-tag" size="small" v-show="ruleAttrList[index].buttonFlag" @click="ruleAttrList[index].formFlag=true;ruleAttrList[index].buttonFlag=false;">+ New Tag</el-button>

            <el-form ref="form" v-show="ruleAttrList[index].formFlag" :model="ruleAttrForm" label-width="80px">
              <el-form-item label="属性规格名称">
                <el-input v-model="ruleAttrForm.attrList"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="insertAttrListByRuleIndex(index)">立即创建</el-button>
                <el-button>取消</el-button>
              </el-form-item>
            </el-form>
          </div>



          <el-form ref="form" v-show="formFlag" :model="ruleAttrForm" label-width="80px">
            <el-form-item label="属性名称">
              <el-input v-model="ruleAttrForm.attrName"></el-input>
            </el-form-item>
              <el-form-item label="属性规格名称">
                <el-input v-model="ruleAttrForm.attrList"></el-input>
              </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="insertRuleAttrList">立即创建</el-button>
              <el-button>取消</el-button>
            </el-form-item>
          </el-form>

          <el-button  class="button-new-tag" v-show="buttonFlag" size="small" @click="buttonFlag=false;formFlag=true">+ New Tag</el-button>





        </el-form-item>
        <el-form-item label="状态位" prop="ruleStatus">
          <el-radio-group v-model="form.ruleStatus">
            <el-radio
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRuleinfo, getRuleinfo, delRuleinfo, addRuleinfo, updateRuleinfo } from "@/api/product/rule";

export default {
  name: "Ruleinfo",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 规格属性表格数据
      ruleinfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ruleName: null,
        ruleStatus: null,
        createdBy: null,
      },

      ruleAttrList:[
       /* {
          attrName:"红色家族",
          attrList:["人","234"]
          ,
          buttonFlag:true,
          formFlag:false,
        },
        {
          attrName:"白色家族",
          attrList:["人","234"],
          buttonFlag:true,
          formFlag:false,
        },
        {
          attrName:"红色家族1111",
          attrList:["人","234"],
          buttonFlag:true,
          formFlag:false,
        }*/
      ],
      buttonFlag:true,
      formFlag:false,

      ruleAttrForm: {
        attrName:"",
        attrList:""
      },

      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /**
     * 删除子集合
     * @param index 父集合 数组下标
     * @param ruleAttrIndex 子集和数组下标
     */
    handleAttrClose(index,ruleAttrIndex){
      //this.ruleAttrList[index].attrList  获取父级 并 获取里面的attrList 属性  attrList属性为数组 所以ruleAttrIndex是他的下标
      //attrList.splice(ruleAttrIndex,1); 删除子集合 数据 个数1个 从数组下标删起
      this.ruleAttrList[index].attrList.splice(ruleAttrIndex,1);
    },

    /**
     * 删除父集合
     * @param index 复集合下标
     */
    handleRuleClose(index){
      // this.ruleAttrList.splice(index,1); 删除父集合 数据 个数1个 从数组下标删起
      this.ruleAttrList.splice(index,1);
    },

    /**
     * 添加所属父集合 得 子集
     * @param index 父级 下标
     */
    insertAttrListByRuleIndex(index){
      let ruleAttrListElement = this.ruleAttrList[index];
      let items = this.ruleAttrForm.attrList;
      let attrList = ruleAttrListElement.attrList;
      let attrListIndex = -1;
      attrList.forEach((item,index) =>{
        if(item === items){
          attrListIndex = index;
        }
      })

      //重复则体是
      if(attrListIndex !== -1){
        this.$modal.msgError(`【${items}】已经在【${ruleAttrListElement.attrName}】中存在`);
      }else{
        //不重复添加
        attrList.push(items);
      }

      //重置对象
      ruleAttrListElement.formFlag=false;
      ruleAttrListElement.buttonFlag=true;
      this.ruleAttrList[index] = ruleAttrListElement;
      this.ruleAttrForm.attrList ="";
    },

    /**
     * 添加集合 对象
     */
    insertRuleAttrList(){
      //转换操作对象 前拷贝
      let ruleAttrForm = this.ruleAttrForm;
      //new 新对象
      let ruleAttrParam ={
        attrName:"",
        attrList:[],
        buttonFlag:true,
        formFlag:false,
      }
      //赋值 等同于 后台 set   将有值得对象赋给  没值得对象 类似于BeanUtils.copyproperties
      ruleAttrParam.attrName = ruleAttrForm.attrName;
      ruleAttrParam.attrList.push(ruleAttrForm.attrList)

      //定义 非数组下标
      let ruleAttrListIndex = -1;
      this.ruleAttrList.forEach((item,index) =>{
        //找到 数组下标为 attrName 相同的  ruleAttrListIndex 改变
        if(ruleAttrParam.attrName === item.attrName){
          ruleAttrListIndex = index;
        }
      })
      //说明数组中不重复直接添加
      if(ruleAttrListIndex === -1){
        this.ruleAttrList.push(ruleAttrParam)
      }else{
        // 数组重复  则逻辑复用 添加子集和逻辑  传入当前重复得 数组下标
        this.insertAttrListByRuleIndex(ruleAttrListIndex)
      }
      //重置
      this.ruleAttrForm = {
        attrName:"",
        attrList:""
      }
      this.buttonFlag = true;
       this.formFlag = false;
    },
    /** 查询规格属性列表 */
    getList() {
      this.loading = true;
      listRuleinfo(this.queryParams).then(response => {
        let ruleinfoList = response.data.rows;

        ruleinfoList.forEach(item =>{
          let ruleAttrTemplateList = JSON.parse(item.ruleAttrTemplate);
          let ruleAttrTemplateListString = "";
          ruleAttrTemplateList.forEach(ruleAttrTemplate =>{
            let attrName = ruleAttrTemplate.attrName;
            ruleAttrTemplateListString = ruleAttrTemplateListString + attrName + ",";
            ruleAttrTemplateListString = ruleAttrTemplateListString.substring(0,ruleAttrTemplateListString.length - 1);
            ruleAttrTemplateListString=ruleAttrTemplateListString+"<br/>"
            ruleAttrTemplateListString = ruleAttrTemplateListString + ruleAttrTemplate.attrList.join(",")
            ruleAttrTemplateListString=ruleAttrTemplateListString+"<br/>"
          })


          item.ruleAttrTemplate = ruleAttrTemplateListString;
        });


        this.ruleinfoList = ruleinfoList;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        ruleName: null,
        ruleAttrTemplate: null,
        ruleStatus: null,
        revision: null,
        createdBy: null,
        createTime: null,
        updatedBy: null,
        updatedTime: null
      };
     // this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加规格属性";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      debugger
      this.reset();
      const id = row.id || this.ids
      getRuleinfo(id).then(response => {
        this.form = response.data;
        this.ruleAttrList = JSON.parse(response.data.ruleAttrTemplate);
        this.open = true;
        this.title = "修改规格属性";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.form.ruleAttrTemplate = JSON.stringify(this.ruleAttrList)
        if (this.form.id != null) {
          updateRuleinfo(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
        } else {
          addRuleinfo(this.form).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          });
        }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除规格属性编号为"' + ids + '"的数据项？').then(function() {
        return delRuleinfo(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('rule/ruleinfo/export', {
        ...this.queryParams
      }, `ruleinfo_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
